/**
 * 餐饮收银系统通用JavaScript
 */

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 移动端菜单切换
    const mobileToggle = document.querySelector('.mobile-nav-toggle');
    const sidebar = document.querySelector('.sidebar');
    const mainContent = document.querySelector('.main-content');
    
    if (mobileToggle && sidebar) {
        mobileToggle.addEventListener('click', function() {
            sidebar.classList.toggle('show');
            
            // 防止菜单打开时页面滚动
            document.body.classList.toggle('sidebar-open');
        });
        
        // 点击主内容区域关闭侧边栏
        if (mainContent) {
            mainContent.addEventListener('click', function(e) {
                if (sidebar.classList.contains('show') && window.innerWidth <= 576) {
                    sidebar.classList.remove('show');
                    document.body.classList.remove('sidebar-open');
                }
            });
        }
        
        // 监听窗口调整大小
        window.addEventListener('resize', function() {
            if (window.innerWidth > 576) {
                sidebar.classList.remove('show');
                document.body.classList.remove('sidebar-open');
            }
        });
    }
    
    // 显示/隐藏消息提示
    initAlerts();
    
    // 初始化事件监听器
    initEventListeners();
    
    // 初始化购物车
    initCart();
    
    // 修复布局问题
    fixLayoutIssues();
});

/**
 * 修复布局问题
 */
function fixLayoutIssues() {
    // 确保内容区域高度至少是视口高度
    const mainContent = document.querySelector('.main-content');
    const sidebar = document.querySelector('.sidebar');
    
    if (mainContent && sidebar) {
        // 调整内容区域最小高度
        const adjustHeight = () => {
            const windowHeight = window.innerHeight;
            mainContent.style.minHeight = `${windowHeight}px`;
            sidebar.style.height = `${windowHeight}px`;
        };
        
        // 初始调整
        adjustHeight();
        
        // 窗口大小改变时调整
        window.addEventListener('resize', adjustHeight);
    }
    
    // 修复表格在移动设备上的显示
    const tables = document.querySelectorAll('.table');
    tables.forEach(table => {
        const wrapper = document.createElement('div');
        wrapper.className = 'table-responsive';
        table.parentNode.insertBefore(wrapper, table);
        wrapper.appendChild(table);
    });
}

/**
 * 初始化提示消息
 */
function initAlerts() {
    const alerts = document.querySelectorAll('.alert');
    
    alerts.forEach(alert => {
        if (alert.classList.contains('alert-dismissible')) {
            const closeBtn = alert.querySelector('.close');
            if (closeBtn) {
                closeBtn.addEventListener('click', function() {
                    alert.style.display = 'none';
                });
            }
            
            // 自动关闭
            if (alert.dataset.autoClose) {
                setTimeout(() => {
                    alert.style.opacity = '0';
                    setTimeout(() => {
                        alert.style.display = 'none';
                    }, 300);
                }, parseInt(alert.dataset.autoClose) * 1000);
            }
        }
    });
}

/**
 * 显示提示消息
 * @param {string} message 消息内容
 * @param {string} type 消息类型 success|warning|danger|info
 * @param {number} autoClose 自动关闭时间(秒)，0表示不自动关闭
 */
function showAlert(message, type = 'info', autoClose = 3) {
    const alertContainer = document.getElementById('alert-container');
    if (!alertContainer) return;
    
    const alert = document.createElement('div');
    alert.className = `alert alert-${type} alert-dismissible fade-in`;
    alert.innerHTML = `
        ${message}
        <button type="button" class="close">&times;</button>
    `;
    
    alertContainer.appendChild(alert);
    
    // 添加关闭按钮事件
    const closeBtn = alert.querySelector('.close');
    if (closeBtn) {
        closeBtn.addEventListener('click', function() {
            alert.classList.add('fade-out');
            setTimeout(() => {
                alertContainer.removeChild(alert);
            }, 300);
        });
    }
    
    // 自动关闭
    if (autoClose > 0) {
        setTimeout(() => {
            alert.classList.add('fade-out');
            setTimeout(() => {
                alertContainer.removeChild(alert);
            }, 300);
        }, autoClose * 1000);
    }
}

/**
 * 初始化事件监听器
 */
function initEventListeners() {
    // 日期选择器
    const datePickers = document.querySelectorAll('.date-picker');
    if (datePickers.length > 0 && typeof flatpickr !== 'undefined') {
        datePickers.forEach(el => {
            flatpickr(el, {
                dateFormat: 'Y-m-d',
                locale: 'zh'
            });
        });
    }
    
    // 确认弹窗
    const confirmBtns = document.querySelectorAll('[data-confirm]');
    confirmBtns.forEach(btn => {
        btn.addEventListener('click', function(e) {
            if (!confirm(this.dataset.confirm || '确定要执行此操作吗？')) {
                e.preventDefault();
                return false;
            }
        });
    });
    
    // Ajax表单提交
    const ajaxForms = document.querySelectorAll('form[data-ajax="true"]');
    ajaxForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('[type="submit"]');
            const originalText = submitBtn ? submitBtn.innerHTML : '';
            
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '处理中...';
            }
            
            fetch(this.action, {
                method: this.method,
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert(data.message || '操作成功', 'success');
                    
                    // 重定向
                    if (data.redirect) {
                        setTimeout(() => {
                            window.location.href = data.redirect;
                        }, 1000);
                    }
                    
                    // 重置表单
                    if (data.reset) {
                        this.reset();
                    }
                    
                    // 回调
                    if (this.dataset.callback) {
                        if (typeof window[this.dataset.callback] === 'function') {
                            window[this.dataset.callback](data);
                        }
                    }
                } else {
                    showAlert(data.message || '操作失败', 'danger');
                }
            })
            .catch(error => {
                showAlert('请求发生错误: ' + error, 'danger');
            })
            .finally(() => {
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            });
        });
    });
}

/**
 * 初始化购物车功能
 */
function initCart() {
    // 添加商品到购物车按钮
    const addToCartBtns = document.querySelectorAll('.add-to-cart');
    
    addToCartBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const productId = this.dataset.id;
            const productName = this.dataset.name;
            const productPrice = parseFloat(this.dataset.price);
            
            addToCart(productId, productName, productPrice);
        });
    });
    
    // 清空购物车按钮
    const clearCartBtn = document.getElementById('clear-cart');
    if (clearCartBtn) {
        clearCartBtn.addEventListener('click', function() {
            clearCart();
        });
    }
    
    // 结账按钮
    const checkoutBtn = document.getElementById('checkout-btn');
    if (checkoutBtn) {
        checkoutBtn.addEventListener('click', function() {
            checkout();
        });
    }
    
    // 初始化加载购物车
    loadCart();
}

/**
 * 添加商品到购物车
 * @param {number} productId 商品ID
 * @param {string} productName 商品名称
 * @param {number} price 价格
 * @param {number} quantity 数量
 */
function addToCart(productId, productName, price, quantity = 1) {
    fetch('/api/cart.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            action: 'add',
            product_id: productId,
            quantity: quantity
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(`已添加 ${productName} 到购物车`, 'success', 2);
            updateCartView();
            
            // 触发购物车更新事件
            const event = new CustomEvent('cartUpdated', { detail: data.cart });
            document.dispatchEvent(event);
        } else {
            showAlert(data.message || '添加失败', 'danger');
        }
    })
    .catch(error => {
        showAlert('请求发生错误: ' + error, 'danger');
    });
}

/**
 * 更新购物车商品数量
 * @param {number} cartItemId 购物车项ID
 * @param {number} quantity 数量
 */
function updateCartItemQuantity(cartItemId, quantity) {
    if (quantity <= 0) {
        removeCartItem(cartItemId);
        return;
    }
    
    fetch('/api/cart.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            action: 'update',
            cart_item_id: cartItemId,
            quantity: quantity
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            updateCartView();
            
            // 触发购物车更新事件
            const event = new CustomEvent('cartUpdated', { detail: data.cart });
            document.dispatchEvent(event);
        } else {
            showAlert(data.message || '更新失败', 'danger');
        }
    })
    .catch(error => {
        showAlert('请求发生错误: ' + error, 'danger');
    });
}

/**
 * 移除购物车商品
 * @param {number} cartItemId 购物车项ID
 */
function removeCartItem(cartItemId) {
    fetch('/api/cart.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            action: 'remove',
            cart_item_id: cartItemId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            updateCartView();
            
            // 触发购物车更新事件
            const event = new CustomEvent('cartUpdated', { detail: data.cart });
            document.dispatchEvent(event);
        } else {
            showAlert(data.message || '移除失败', 'danger');
        }
    })
    .catch(error => {
        showAlert('请求发生错误: ' + error, 'danger');
    });
}

/**
 * 清空购物车
 */
function clearCart() {
    fetch('/api/cart.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            action: 'clear'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('购物车已清空', 'success', 2);
            updateCartView();
            
            // 触发购物车更新事件
            const event = new CustomEvent('cartUpdated', { detail: [] });
            document.dispatchEvent(event);
        } else {
            showAlert(data.message || '清空失败', 'danger');
        }
    })
    .catch(error => {
        showAlert('请求发生错误: ' + error, 'danger');
    });
}

/**
 * 加载购物车内容
 */
function loadCart() {
    fetch('/api/cart.php?action=get', {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            updateCartView(data.items);
            
            // 更新购物车图标数量
            updateCartBadge(data.total_count);
            
            // 更新合计金额
            const cartTotalAmount = document.getElementById('cart-total-amount');
            if (cartTotalAmount) {
                cartTotalAmount.textContent = '¥' + parseFloat(data.total_amount).toFixed(2);
            }
        } else {
            showAlert(data.message, 'danger');
        }
    })
    .catch(error => {
        console.error('加载购物车失败:', error);
    });
}

/**
 * 更新购物车视图
 * @param {Array} cart 购物车数据
 */
function updateCartView(cart = null) {
    const cartContainer = document.getElementById('cart-container');
    if (!cartContainer) return;
    
    // 清空购物车容器
    cartContainer.innerHTML = '';
    
    // 检查购物车是否为空
    if (!cart || cart.length === 0) {
        cartContainer.innerHTML = '<div class="empty-cart">购物车是空的</div>';
        
        // 更新合计金额
        const cartTotalAmount = document.getElementById('cart-total-amount');
        if (cartTotalAmount) {
            cartTotalAmount.textContent = '¥0.00';
        }
        
        return;
    }
    
    // 创建购物车项容器
    const cartItemsContainer = document.createElement('div');
    cartItemsContainer.className = 'cart-items';
    
    // 添加购物车项
    let totalAmount = 0;
    
    cart.forEach(item => {
        const subtotal = parseFloat(item.price) * parseInt(item.quantity);
        totalAmount += subtotal;
        
        const cartItemElement = document.createElement('div');
        cartItemElement.className = 'cart-item';
        cartItemElement.dataset.id = item.id;
        cartItemElement.dataset.productId = item.product_id;
        
        cartItemElement.innerHTML = `
            <div class="cart-item-details">
                <div class="cart-item-name">${item.product_name}</div>
                <div class="cart-item-price">¥${parseFloat(item.price).toFixed(2)}</div>
            </div>
            <div class="cart-item-quantity">
                <button class="quantity-btn quantity-decrease" data-id="${item.id}">-</button>
                <span class="quantity-value">${item.quantity}</span>
                <button class="quantity-btn quantity-increase" data-id="${item.id}">+</button>
            </div>
            <div class="cart-item-subtotal">¥${subtotal.toFixed(2)}</div>
            <button class="cart-item-remove" data-id="${item.id}">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        cartItemsContainer.appendChild(cartItemElement);
    });
    
    // 添加到购物车容器
    cartContainer.appendChild(cartItemsContainer);
    
    // 更新合计金额
    const cartTotalAmount = document.getElementById('cart-total-amount');
    if (cartTotalAmount) {
        cartTotalAmount.textContent = '¥' + totalAmount.toFixed(2);
    }
    
    // 添加事件监听器
    // 数量减少按钮
    const decreaseBtns = cartContainer.querySelectorAll('.quantity-decrease');
    decreaseBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const itemId = this.dataset.id;
            const quantityElement = this.parentElement.querySelector('.quantity-value');
            let quantity = parseInt(quantityElement.textContent) - 1;
            
            // 最低数量为1
            quantity = Math.max(1, quantity);
            
            // 更新数量
            updateCartItemQuantity(itemId, quantity);
        });
    });
    
    // 数量增加按钮
    const increaseBtns = cartContainer.querySelectorAll('.quantity-increase');
    increaseBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const itemId = this.dataset.id;
            const quantityElement = this.parentElement.querySelector('.quantity-value');
            let quantity = parseInt(quantityElement.textContent) + 1;
            
            // 更新数量
            updateCartItemQuantity(itemId, quantity);
        });
    });
    
    // 移除按钮
    const removeBtns = cartContainer.querySelectorAll('.cart-item-remove');
    removeBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const itemId = this.dataset.id;
            removeCartItem(itemId);
        });
    });
}

/**
 * 更新购物车徽章数量
 * @param {number} count 购物车商品数量
 */
function updateCartBadge(count) {
    const cartBadge = document.querySelector('.cart-badge');
    if (cartBadge) {
        cartBadge.textContent = count;
        cartBadge.style.display = count > 0 ? 'inline-block' : 'none';
    }
}

/**
 * 结账处理
 */
function checkout() {
    // 不再跳转到checkout.php
    // 直接显示模态框，事件处理在products.php中
    const checkoutModal = document.getElementById('checkoutModal');
    if (checkoutModal) {
        $('#checkoutModal').modal('show');
    } else {
        console.error('结账模态框不存在，请确保在当前页面');
    }
}

/**
 * AJAX请求
 * @param {string} url 请求地址
 * @param {string} method 请求方法
 * @param {Object} data 请求数据
 * @param {Function} successCallback 成功回调
 * @param {Function} errorCallback 失败回调
 */
function ajaxRequest(url, method, data, successCallback, errorCallback) {
    const options = {
        method: method,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    };
    
    if (method.toUpperCase() === 'POST') {
        options.headers['Content-Type'] = 'application/json';
        options.body = JSON.stringify(data);
    }
    
    fetch(url, options)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (typeof successCallback === 'function') {
                    successCallback(data);
                }
            } else {
                if (typeof errorCallback === 'function') {
                    errorCallback(data);
                } else {
                    showAlert(data.message || '操作失败', 'danger');
                }
            }
        })
        .catch(error => {
            if (typeof errorCallback === 'function') {
                errorCallback({ success: false, message: '请求发生错误: ' + error });
            } else {
                showAlert('请求发生错误: ' + error, 'danger');
            }
        });
} 